//
//  LoginPwdView.swift
//  casdon_swiftUI
//
//  Created by ww on 2025/3/30.
//

import SwiftUI
import _AuthenticationServices_SwiftUI
import FlowStacks


struct LoginPwdView: View {
    @StateObject var viewModel = LoginPwdViewModel()
    @State var showTxAuthVC = true // 控制一键登录页面的展示与消失
    @State var showModal = false
    @State var showEnvironment = false
    @State var showAgreementAlert = false
    @EnvironmentObject var navigator: FlowNavigator<LoginStack>
    
    let leftOffset = 24.0

    var body: some View {
        ZStack(alignment: .topTrailing){
            if !AuthManager.shared.isLoggedIn && showTxAuthVC {
                TXAuthViewController(token: $viewModel.txtoken, show: $showTxAuthVC)
            }
           
                EnvironmentEntry(showSheet: $showEnvironment)
                    .padding(.trailing, 20)
                    .padding(.top, 14)
            
            VStack(alignment: .leading) {
                NavigationBar(title: "", isBackBtnVisible: true, onBack: {
                    showTxAuthVC = true
                })
                HStack(alignment: .center, content: {
                    Spacer()
                    HeaderView()
                    Spacer()
                }).padding(.top, 44)

                // 输入框部分
                VStack {
                    // 账号输入框
                    CustomTextField(
                        text: $viewModel.account,
                        placeholder: "email or phoneNum",
                        isValid: viewModel.account.isEmpty || viewModel.account.isEmail || viewModel.account.isPhoneNum
                    )
                    .disabled(viewModel.isLoading)
                    // 密码输入框
                    CustomSecureField(
                        text: $viewModel.password,
                        placeholder: "password",
                        isSecure: $viewModel.isPasswordHidden
                    )
                    .disabled(viewModel.isLoading)
                }
                .padding(.horizontal, leftOffset)
                .padding(.top, 48)
                AgreeView(isAgree: $viewModel.isAgreed)
                    .padding(.leading, leftOffset)
                    .padding(.top, 15)

                // 登录按钮
                HStack {
                    Button(action: {
                        if viewModel.isAgreed {
                            viewModel.login()
                        }
                        else{
                            showAgreementAlert = true
                        }
                    }) {
                        ZStack {
                            if viewModel.isLoading {
                                ProgressView()
                                    .progressViewStyle(CircularProgressViewStyle(tint: .white))
                            } else {
                                Text("login")
                                    .font(.system(size: 16, weight: .medium))
                            }
                        }
                        .frame(maxWidth: .infinity)
                        .frame(height: 44)
                        .background((viewModel.isInputValid && !viewModel.isLoading) ? AppColors.Brand6 : AppColors.Brand6.opacity(0.5))
                        .cornerRadius(6)
                        .foregroundColor(.white)
                        .contentShape(Rectangle())
                    }
                    .disabled(viewModel.isLoading || !viewModel.isInputValid)
                    .padding(.horizontal, leftOffset)
                }.padding(.top, 25)

                // 新用户注册
                HStack {
                    Button("Register") {
                        navigator.push(.register)
                    }.foregroundColor(AppColors.Gy2)
                        .font(.system(size: 14))
                        .padding(.leading, leftOffset)
                    Spacer()
                    Button("forget password") {
                        navigator.push(.forgetPwd)
                    }.foregroundColor(AppColors.Gy2)
                        .font(.system(size: 14))
                        .padding(.leading, leftOffset)
                    Spacer()
                    Button("login with sms") {
                        navigator.push(.loginSms)
                    }.foregroundColor(AppColors.Gy2)
                        .font(.system(size: 14))
                        .padding(.trailing, leftOffset)
                }
                .padding(.top, 15)
                Spacer()
                HStack {
                    Rectangle()
                        .frame(maxWidth: .infinity)
                        .frame(height: 1)
                        .foregroundColor(AppColors.Gray2)
                    Text("other login type")
                        .font(.system(size: 14))
                        .foregroundColor(AppColors.Gy3)
                    Rectangle()
                        .frame(maxWidth: .infinity)
                        .frame(height: 1)
                        .foregroundColor(AppColors.Gray2)
                }.padding(.horizontal, 24)
                    .padding(.bottom, 25)
                HStack {
                    Spacer()
                    Button(action: {
                        viewModel.wechatLogin()
                        
                    }, label: {
                        Image("login_wechat")
                    })
                    Spacer()
                    Button(action: {
                        viewModel.appleLogin()
                    }, label: {
                        Image("login_apple")
                    })
                    Spacer()
                }.padding(.horizontal, 24)
                    .padding(.bottom, 48)
            }
            if viewModel.showAlert, let config = viewModel.alertConfig {
                            Color.black.opacity(0.4)
                                .ignoresSafeArea()

                            CustomAlertView(
                                title: config.title,
                                message: config.message,
                                buttons: config.buttons
                            )
                            .transition(.scale)
            }
            
            if showAgreementAlert == true{
                AgreementPopupOverlay(
                    onTapUserAgreement: { print("用户协议点击") },
                    onTapPrivacyPolicy: { print("隐私政策点击") },
                    onDecline: { viewModel.isAgreed = false ; showAgreementAlert = false },
                    onConfirm: {
                        viewModel.isAgreed = true
                        showAgreementAlert = false
                    }
                )
            }
        }
        .sheet(isPresented: $showEnvironment, content: {
            EnvironmentSelectionSheet()
        })
        // 微信登录返回
        .onOpenURL(perform: { url in
            viewModel.handleOpenURL(url: url)
        })
        .toast(isPresented:$viewModel.showToast , message: viewModel.toastMsg)
    }
}

#Preview {
   // LoginPwdView()
}
